﻿using BodaNetCommunications.Cores;
using BodaNetCommunications.ModbusComs.ModbusUtil;
using BodaNetCommunications.Utilities.Attributes;
using BodaNetCommunications.Utilities.ComTypes;
using BodaNetCommunications.Utilities.Results;

namespace BodaNetCommunications.ModbusComs
{
    [ProtocolTypeAttribute(ProtocolType.ModbusTcp)]
    public class ModbusTcpCommService : CommReadWrite, IModbusTcpCommService
    {
        public ConnectionOptions Options { get; private set; }

        public ModbusTcp Plc { get; private set; }

        public bool IsConnected => Plc != null && Plc.IsConnected;

        public ModbusTcpCommService()
        {
            base._byteTransform = new ModbusByteTransformBase();
        }

        public BodaResult Connect(ConnectionOptions connectionOptions)
        {
            Options = connectionOptions;

            if (IsConnected)
            {
                _byteTransform.IsStringReverseByteWord = connectionOptions.StringReverse;
                _byteTransform.EndianType = connectionOptions.EndianType;
                if (Plc != null)
                {
                    Plc.EndianType = connectionOptions.EndianType;
                    Plc.FirstAddress = connectionOptions.FirstAddress;
                }


                BodaResult bodaResult = new BodaResult();
                bodaResult.IsSuccess = true;
                bodaResult.Message = $"ModbusTcp【{Options.Ip}:{Options.Port}】的连接已经在线，不需要重复连接";
                return bodaResult;
            }

            Plc = new ModbusTcp();
            Plc.EndianType = connectionOptions.EndianType;
            Plc.FirstAddress = connectionOptions.FirstAddress;

            _byteTransform.IsStringReverseByteWord = connectionOptions.StringReverse;
            _byteTransform.EndianType = connectionOptions.EndianType;

            // 切换Modbus字节长度判断
            base.WordLength = 1;

            var resConnect = Plc.Connect(connectionOptions);
            return resConnect;
        }

        /// <summary>
        /// 重写基础数据的读取功能
        /// </summary>
        /// <param name="address">数据地址</param>
        /// <param name="length">数据个数</param>
        /// <returns></returns>
        public override BodaResult<byte[]> Read(string address, ushort length)
        {
            BodaResult<byte[]>? readResult = new BodaResult<byte[]>();
            if (Plc == null)
            {
                readResult.IsSuccess = false;
                readResult.Message = "PLC实例为空";
                return readResult;
            }
            var res = Plc.Read(address, length);
            if (res.IsSuccess)
            {
                readResult.Content = res.DataBytes.ToArray();
            }
            else
            {
                readResult.IsSuccess = false;
                readResult.Message = res.Message;
            }
            return readResult;
        }

        public override BodaResult Write(string address, byte[] value)
        {
            var res = Plc.Write(address, value);
            return res;
        }


        public void Disconnect()
        {
            Plc?.Disconnect();
        }

        public BodaResult<byte> ReceiveMsg(int timeout = 2000, int bytesLen = 1024)
        {
            throw new NotImplementedException();
        }

        public BodaResult SendMsgc(byte[] bytes, int timeout = 1500)
        {
            throw new NotImplementedException();
        }

        public void Dispose()
        {
            Disconnect();
        }
    }
}
